package com.newjiabo.system.service.impl;

import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import com.newjiabo.common.utils.DateUtils;
import com.newjiabo.common.utils.SnowFlake;
import com.newjiabo.system.domain.vo.RegionQuery;
import com.newjiabo.system.domain.vo.RegionVO;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import com.newjiabo.system.mapper.SysRegionMapper;
import com.newjiabo.system.domain.SysRegion;
import com.newjiabo.system.service.ISysRegionService;

import javax.annotation.Resource;

/**
 * 行政地区Service业务层处理
 *
 * @author CaoMengHui
 * @date 2023-09-18
 */
@Service
public class SysRegionServiceImpl implements ISysRegionService {

    @Resource
    private SysRegionMapper sysRegionMapper;

    /**
     * 查询行政地区
     *
     * @param id 行政地区主键
     * @return 行政地区
     */
    @Override
    public SysRegion selectSysRegionById(String id) {
        return sysRegionMapper.selectSysRegionById(id);
    }

    /**
     * 查询行政地区列表
     *
     * @param sysRegion 行政地区
     * @return 行政地区
     */
    @Override
    public List<SysRegion> selectSysRegionList(SysRegion sysRegion) {
        return sysRegionMapper.selectSysRegionList(sysRegion);
    }

    /**
     * 新增行政地区
     *
     * @param sysRegion 行政地区
     * @return 结果
     */
    @Override
    public int insertSysRegion(SysRegion sysRegion) {
        sysRegion.setId(SnowFlake.getIdStr());
        sysRegion.setCreateTime(DateUtils.getNowDate());
        return sysRegionMapper.insertSysRegion(sysRegion);
    }

    /**
     * 修改行政地区
     *
     * @param sysRegion 行政地区
     * @return 结果
     */
    @Override
    public int updateSysRegion(SysRegion sysRegion) {
        sysRegion.setUpdateTime(DateUtils.getNowDate());
        return sysRegionMapper.updateSysRegion(sysRegion);
    }

    /**
     * 批量删除行政地区
     *
     * @param ids 需要删除的行政地区主键
     * @return 结果
     */
    @Override
    public int deleteSysRegionByIds(String[] ids) {
        return sysRegionMapper.deleteSysRegionByIds(ids);
    }

    /**
     * 删除行政地区信息
     *
     * @param id 行政地区主键
     * @return 结果
     */
    @Override
    public int deleteSysRegionById(Long id) {
        return sysRegionMapper.deleteSysRegionById(id);
    }

    @Override
    public List<SysRegion> getItem(String id) {
        RegionQuery regionQuery = new RegionQuery();
        regionQuery.setParentId(id);
        List<SysRegion> regions = this.selectByQuery(regionQuery);
        regions.sort(Comparator.comparing(SysRegion::getOrderNum));
        return regions;
    }

    @Override
    public Map<String, Object> getRegion(String cityCode, String townName) {
        //获取地址信息
        SysRegion region = this.getOneByCityCodeAndName(cityCode,townName);
        if (region != null) {
            //获取它的层级关系
            String path = region.getPath();
            String[] result = path.split(",");
            //因为有无用数据 所以先删除前两个
            result = ArrayUtils.remove(result, 0);
            result = ArrayUtils.remove(result, 0);
            //地址id
            StringBuilder regionIds = new StringBuilder();
            //地址名称
            StringBuilder regionNames = new StringBuilder();
            //循环构建新的数据
            for (String regionId : result) {
                SysRegion reg = this.selectSysRegionById(regionId);
                if (reg != null) {
                    regionIds.append(regionId).append(",");
                    regionNames.append(reg.getName()).append(",");
                }
            }
            regionIds.append(region.getId());
            regionNames.append(region.getName());
            //构建返回数据
            Map<String, Object> obj = new HashMap<>(2);
            obj.put("id", regionIds.toString());
            obj.put("name", regionNames.toString());
            return obj;
        }
        return Collections.emptyMap();
    }

    @Override
    public String getItemByLastName(String lastName) {
        return null;
    }

    @Override
    public List<RegionVO> getAllCity() {
        List<SysRegion> regions = this.getInLeven("city", "province");
        return this.regionTree(regions);
    }

    @Override
    public List<RegionVO> getAllCounty() {
        //查询所有省市
        List<SysRegion> regions = this.getInLeven("city", "province","district");
        List<RegionVO> regionVOS = this.regionTree(regions);
        regions.stream().filter(region -> ("district").equals(region.getLevel())).forEach(item ->{
            for (RegionVO region : regionVOS) {
                for (RegionVO regionVO : region.getChildren()){
                    if(regionVO.getId().equals(item.getParentId())){
                        regionVO.getChildren().add(new RegionVO(item));
                    }
                }
            }
        });
        return regionVOS;
    }

    /**
     * in leven
     *
     * @author CaoMengHui.
     * @date 2023/9/18 15:33
     * @param values
     * @return
     */
    private List<SysRegion> getInLeven(String... values) {
        return sysRegionMapper.getInLeven(values);
    }

    private SysRegion getOneByCityCodeAndName(String cityCode, String townName) {
        List<SysRegion> oneByCityCodeAndName = sysRegionMapper.getOneByCityCodeAndName(cityCode, townName);
        if(CollectionUtil.isNotEmpty(oneByCityCodeAndName)){
            return oneByCityCodeAndName.get(0);
        }
        return null;
    }

    public List<SysRegion> selectByQuery(RegionQuery query) {
//        query.setDeleteFlag(false);
        List<SysRegion> regions = sysRegionMapper.selectByQuery(query);
        return regions;
    }

    private List<RegionVO> regionTree(List<SysRegion> regions) {
        List<RegionVO> regionVOS = new ArrayList<>();
        regions.stream().filter(region -> ("province").equals(region.getLevel())).forEach(item -> regionVOS.add(new RegionVO(item)));
        regions.stream().filter(region -> ("city").equals(region.getLevel())).forEach(item -> {
            for (RegionVO region : regionVOS) {
                if (region.getId().equals(item.getParentId())) {
                    region.getChildren().add(new RegionVO(item));
                }
            }
        });
        return regionVOS;
    }

}
